package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.dto.BedDto;
import com.zzyl.entity.Bed;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.BedMapper;
import com.zzyl.mapper.ElderMapper;
import com.zzyl.service.BedService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.BedVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BedServiceImpl implements BedService {
    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Override
    public List<BedVo> getBedsByRoomId(Long roomId) {
        return bedMapper.getBedsByRoomId(roomId);
    }

    @Override
    public int addBed(BedDto bedDto) {
        //TODO:是否需要重名判断
        //dto=>entity
        Bed bed = BeanUtil.copyProperties(bedDto, Bed.class);
        bed.setBedStatus(0);//默认床位状态为0(未入住)
        int num = bedMapper.countByBedNumber(bed.getBedNumber());
        if (num > 0) {
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_DUPLICATE_BED_NUMBER);
        }
        return bedMapper.insert(bed);
    }

    //根据id删除床位
    @Override
    public int deleteById(Long id) {
        //TODO:床位有人是否删除
        int count = elderMapper.countByBedId(id);
        if (count > 0) {
            throw new BaseException(BasicEnum.BED_DELETE_FAIL_ELDER_EXIST);
        }


        return bedMapper.deleteById(id);
    }

    @Override
    public BedVo selectById(Long id) {
        Bed bed = bedMapper.selectById(id);
        return BeanUtil.copyProperties(bed, BedVo.class);
    }

    @Override
    public int updateBed(BedDto bedDto) {
        BedVo bedVo = selectById(bedDto.getId());
        bedVo.setSort(bedDto.getSort());
        bedVo.setBedNumber(bedDto.getBedNumber());
        if (bedDto.getBedStatus() != null) {
            bedVo.setBedStatus(bedDto.getBedStatus());
        }
        Bed bed = BeanUtil.copyProperties(bedVo, Bed.class);
        bed.setCreateTime(LocalDateTime.now());
        bed.setCreateBy(1L);
        return bedMapper.updateBed(bed);
    }
}

